package com.yimi.yinhepda.views.load_module;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.pda.uce.commom.pickerview.builder.OptionsPickerBuilder;
import com.pda.uce.commom.pickerview.listener.OnOptionsSelectListener;
import com.pda.uce.commom.pickerview.view.OptionsPickerView;
import com.pda.ym.entity.response.NoDataResponse;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.SelectMoreTaskNoAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.CarPlateTableDao;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.LineVoTableDao;
import com.yimi.yinhepda.db.dao.UCDeptTableDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.pda.ym.db.table.CarPlateTable;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.db.table.LineVoTable;
import com.yimi.yinhepda.db.table.UCDeptTable;
import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.entity.LoadTaskEntity;
import com.yimi.yinhepda.entity.bean.CarNoEntity;
import com.yimi.yinhepda.entity.bean.LoaderEntity;
import com.yimi.yinhepda.entity.bean.NextDeptEntity;
import com.yimi.yinhepda.entity.bean.NextDeptTaskEntity;
import com.pda.ym.utils.ProvinceEnum;
import com.yimi.yinhepda.entity.bean.VehicleEntity;
import com.yimi.yinhepda.entity.request.CreateLoadTaskRequest;
import com.yimi.yinhepda.entity.request.QueryLoadTaskByStowageRequest;
import com.yimi.yinhepda.entity.request.QueryNextDeptRequest;
import com.yimi.yinhepda.entity.response.QueryCarNoResponse;
import com.yimi.yinhepda.entity.response.QueryLoadTask;
import com.yimi.yinhepda.entity.response.QueryLoadTaskByStowageResponse;
import com.yimi.yinhepda.entity.response.QueryNextDeptResponse;
import com.yimi.yinhepda.entity.response.QueryVehicleAttributeResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.CarNoSelectDialog;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SoundVibratorManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author: lj
 * Date: 2019/7/2 15:26
 * Description:创建装车任务界面
 */
public class CreateLoadTaskActivity extends LoadBaseActivity {

    private ImageButton ibBack;
    /**
     * 省市车牌
     */
    private Button btnCarPlate;
    /**
     * 车牌号码
     */
    private EditText etCarNo;
    /**
     * 选择下一站
     */
    private LinearLayout btnSelNextStation;
    /**
     * 班次日期
     */
    private TextView tvDate;
    /**
     * 临时转换的车牌号
     */
    private String mTempCarNo = "";
    /**
     * 下一部门任务
     */
    private List<NextDeptTaskEntity> mTaskEntityList;
    /**
     * 下一部门实体
     */
    private NextDeptEntity mDeptEntity;
    /**
     * 下一站名称
     */
    private TextView tvNextDeptName;
    /**
     * 预计发车时间
     */
    private TextView tvPlanStartTime;
    /**
     * 任务号
     */
    private TextView tvTaskNo;
    /**
     * 班次
     */
    private TextView tvShift;
    /**
     * 任务号 线性布局
     */
    private LinearLayout llTaskNo;
    /**
     * 预计发车时间  线性布局
     */
    private LinearLayout llPlaneStartTime;
    /**
     * 班次 线性布局
     */
    private LinearLayout llShift;
    /**
     * 班次选项
     */
    private int isOptions1;
    /**
     * 班次数据
     */
    private List<String> mShiftList;
    /**
     * 线路表
     */
    private LineVoTable mLineVoTable;
    /**
     * 0-快运，1-快递，3-融合
     */
    private int mergeDeptType;
    /**
     * 分下一站拨无任务
     */
    boolean fenBoNoTask = false;
    /**
     * 当前为分拨标志
     */
    boolean currentFenBo = false;
    /**
     * 下一站分拨标志
     */
    private boolean nextFenBo = false;
    /**
     * 是否修改车牌号标志
     */
    private boolean changeCarNo;
    /**
     * 车辆属性实体
     */
    private CarNoEntity mCarNoEntity;
    private DepartmentTableDao mDepartmentTableDao;

    public CreateLoadTaskActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "创建装车任务";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_load_task);

        ibBack = findViewById(R.id.ib_back);
        btnCarPlate = findViewById(R.id.btn_carPlate);
        etCarNo = findViewById(R.id.et_carNo);
        btnSelNextStation = findViewById(R.id.ll_select_next_dept);
        tvNextDeptName = findViewById(R.id.tv_next_dept_name);
        tvPlanStartTime = findViewById(R.id.tv_plan_start_time);
        tvTaskNo = findViewById(R.id.tv_task_no);
        tvDate = findViewById(R.id.tv_date);
        tvShift = findViewById(R.id.tv_shift);
        llTaskNo = findViewById(R.id.ll_task_no);
        llPlaneStartTime = findViewById(R.id.ll_plane_start_time);
        llShift = findViewById(R.id.ll_shift);

        ibBack.setOnClickListener(this);
        tvDate.setOnClickListener(this);
        tvShift.setOnClickListener(this);
        btnSelNextStation.setOnClickListener(this);
        btnCarPlate.setOnClickListener(this);
        btnSelNextStation.setOnClickListener(this);
        findViewById(R.id.btn_create).setOnClickListener(this);
        etCarNo.addTextChangedListener(new AddTextChangedListener());

        mDepartmentTableDao = new DepartmentTableDao();

        //设置车牌
        List<CarPlateTable> carPlateTables = new CarPlateTableDao().getAllData();
        if (carPlateTables != null) {
            if (carPlateTables.size() > 0) {
                btnCarPlate.setText(carPlateTables.get(0).getCarPlate());
            }
        }

        int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        if (deptType != 5 && deptType != 6) {
            //网点初始设置班次
            tvDate.setText(DateHelper.getDateFormate(new Date()));
            tvShift.setText("01");
        }

        //设置班次数据源
        mShiftList = new ArrayList<>();
        mShiftList.add("01");
        mShiftList.add("02");
        mShiftList.add("03");
        mShiftList.add("04");
        mShiftList.add("05");
        mShiftList.add("06");
        mShiftList.add("07");
        mShiftList.add("08");
        mShiftList.add("09");
        mShiftList.add("10");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.btn_carPlate:
                //省市车牌
                CarNoSelectDialog.showCarPlateDialog(this, new CarNoSelectDialog.CarNoSelectListener() {
                    @Override
                    public void onclick(String carPlate) {
                        btnCarPlate.setText(carPlate);
                    }
                });
                break;
            case R.id.ll_select_next_dept:
                //选择下一站
                if ("".equals(etCarNo.getText().toString())) {
                    showToast("请先输入或扫描车牌号！");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                String carNo = btnCarPlate.getText().toString() + etCarNo.getText().toString();
                if ("".equals(tvNextDeptName.getText().toString())) {
                    //请求接口拉取下一部门
                    requestQueryNextDept(carNo);
                } else if (changeCarNo) {
                    changeCarNo = false;
                    //车牌号被修改，则重新请求接口查询下一站
                    requestQueryNextDept(carNo);
                } else {
                    showMoreNextDeptDialog(mTaskEntityList);
                }
                break;
            case R.id.tv_date:
                //班次日期
                String clockDate = DateHelper.getDateFormate(new Date());
                //获得选择日期的当前时间戳
                long selectTextTime = DateHelper.getDate(clockDate).getTime();
                TimePickerDialog timePickerDialog = new TimePickerDialog.Builder().setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String time = DateHelper.getDateToString(millseconds, DateHelper.dateFormat);
                        if (time.length() > 9) {
                            time = time.substring(0, 10);
                        }
                        tvDate.setText(time);
                    }
                })
                        .setCancelStringId("取消")
                        .setSureStringId("确定")
                        .setTitleStringId("选择")
                        .setYearText("年")
                        .setMonthText("月")
                        .setDayText("日")
                        .setCyclic(false)
//                        //设置能获取的最小值getMills（）是获取时间毫秒值
                        .setMinMillseconds(DateHelper.getDifferenceTime(0))
//                        //设置能到达的最大值
//                        .setMaxMillseconds(System.currentTimeMillis())
                        //设置当前时间
                        .setCurrentMillseconds(selectTextTime)
                        .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                        .setType(Type.YEAR_MONTH_DAY)
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.timepicker_dialog_bg))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
                        .setWheelItemTextSize(12)
                        .build();
                timePickerDialog.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;
            case R.id.tv_shift:
                //班次号
                OptionsPickerView<String> problemOptions = new OptionsPickerBuilder(this,
                        new OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                isOptions1 = options1;
                                tvShift.setText(mShiftList.get(options1));
                            }
                        })
                        //确定按钮文字
                        .setSubmitText("确定")
                        //取消按钮文字
                        .setCancelText("取消")
                        //确定按钮文字颜色
                        .setSubmitColor(Color.BLACK)
                        //取消按钮文字颜色
                        .setCancelColor(Color.BLACK)
                        //滚轮文字大小
                        .setContentTextSize(20)
                        //循环与否
                        .setCyclic(false, false, false)
                        //设置默认选中项
                        .setSelectOptions(isOptions1)
                        //是否显示为对话框样式
                        .isDialog(false)
                        .build();
                //添加数据源
                problemOptions.setPicker(mShiftList);
                problemOptions.show();
                break;
            case R.id.btn_create:
                //创建
                if ("".equals(etCarNo.getText().toString())) {
                    showToast("请先输入或扫描车牌号！");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                if ("".equals(tvNextDeptName.getText().toString())) {
                    showToast("请先选择下一站！");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                DepartmentTable departmentTable = mDepartmentTableDao.queryDeptByDeptCode(mDeptEntity.getNextDeptCode());
                if (departmentTable != null) {
                    //快运需校验班次
                    if (departmentTable.getIsOmg() == 0) {
                        if ("".equals(tvDate.getText().toString())) {
                            showToast("请选择班次日期！");
                            SoundVibratorManager.playSound(2);
                            return;
                        }
                        if ("".equals(tvShift.getText().toString())) {
                            showToast("请选择班次！");
                            SoundVibratorManager.playSound(2);
                            return;
                        }
                    }
                }
                //请求接口创建配载单
                createLoadTask();
                break;
            default:
                break;
        }
    }

    @Override
    protected void handleBarCode(String result) {
        if (result.contains(Common.SP_C_)) {
            String carNo = etCarNo.getText().toString();
            if (!"".equals(carNo) && !"".equals(mTempCarNo) && carNo.equalsIgnoreCase(mTempCarNo)) {
                //请求接口拉取下一部门
                requestQueryNextDept(btnCarPlate.getText().toString() + carNo);
            } else {
                btnCarPlate.setText(ProvinceEnum.getByCode(result.split(Common.SP_C_)[0]).getName());
                etCarNo.setText(result.split(Common.SP_C_)[1]);
            }
        }
    }

    /**
     * 创建装车任务请求
     */
    private void createLoadTask() {

        showPgDlg("查询线路中...");
        mergeDeptType = 0;
        //分拨无任务号标志
        fenBoNoTask = false;
        currentFenBo = false;
        nextFenBo = false;
        final int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                //查询网点类型是否是快递
                DepartmentTable departmentTable = mDepartmentTableDao.queryDeptByDeptCode(mDeptEntity.getNextDeptCode());
                if (departmentTable != null) {
                    mergeDeptType = departmentTable.getIsOmg();
                    if (departmentTable.getIsOmg() == 1) {
                        if (departmentTable.getDeptType() == 5 || departmentTable.getDeptType() == 6) {
                            nextFenBo = true;
                        }
                        if (deptType == 5 || deptType == 6) {
                            currentFenBo = true;
                        }
                    } else {
                        mLineVoTable = new LineVoTableDao().findLine(sharedPreferUtil.getDeptCode(), mDeptEntity.getNextDeptCode());
                        if (deptType == 5 || deptType == 6) {
                            currentFenBo = true;
                            //分拨查询，下一站是否为分拨
                            if (departmentTable != null) {
                                if (departmentTable.getDeptType() == 5 || departmentTable.getDeptType() == 6) {
                                    nextFenBo = true;
                                    if (mDeptEntity.getTaskNo() == null || "".equals(mDeptEntity.getTaskNo())) {
                                        fenBoNoTask = true;
                                    }
                                }
                            }
                        }
                    }
                } else {
                    mergeDeptType = 2;
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                //快运校验以下规则
                if (mergeDeptType == 0) {
                    if (mLineVoTable == null) {
                        dismissPgDlg();
                        MyDialog.showAlertDialog(CreateLoadTaskActivity.this, "当前出发部门没有到达所选部门的路由线路！");
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                    if ("支线(自有运力)".equals(mDeptEntity.getUseType()) && mDeptEntity.getTaskNo() != null && "".equals(mDeptEntity.getTaskNo())) {
                        dismissPgDlg();
                        MyDialog.showAlertDialog(CreateLoadTaskActivity.this, "自有车辆无任务号，不可创建！");
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                    if (fenBoNoTask) {
                        dismissPgDlg();
                        MyDialog.showAlertDialog(CreateLoadTaskActivity.this, "下一站分拨无任务号，不可创建！");
                        SoundVibratorManager.playSound(2);
                        return;
                    }
                }

                CreateLoadTaskRequest request = new CreateLoadTaskRequest();
                if (currentFenBo && nextFenBo) {
                    //干线
                    request.setBizTypeCode(1);
                } else {
                    //支线
                    request.setBizTypeCode(2);
                }
                if (mDeptEntity.getCarModel() != null) {
                    request.setCarModel(mDeptEntity.getCarModel());
                } else if (mCarNoEntity != null) {
                    //车辆属性：车型
                    request.setCarModel(mCarNoEntity.getVehicleType());
                }
                if (mDeptEntity.getCarNo() != null) {
                    request.setCarNo(mDeptEntity.getCarNo());
                } else if (mCarNoEntity != null) {
                    request.setCarNo(mCarNoEntity.getVehNo());
                }
                request.setTaskNo(mDeptEntity.getTaskNo());
                request.setDestDeptCode(mDeptEntity.getNextDeptCode());
                request.setDestDeptName(mDeptEntity.getNextDeptName());
                if (mDeptEntity.getDriverCode() != null) {
                    request.setDriverCode(mDeptEntity.getDriverCode());
                } else if (mCarNoEntity != null) {
                    request.setDriverCode(mCarNoEntity.getDriverNo());
                }
                if (mDeptEntity.getDriverName() != null) {
                    request.setDriverName(mDeptEntity.getDriverName());
                } else if (mCarNoEntity != null) {
                    request.setDriverName(mCarNoEntity.getDriverName());
                }
                if (mDeptEntity.getDriverPhone() != null) {
                    request.setDriverPhone(mDeptEntity.getDriverPhone());
                } else if (mCarNoEntity != null) {
                    request.setDriverPhone(mCarNoEntity.getDriverTele());
                }
                request.setEndcode(mDeptEntity.getEndcode());
                request.setG7SupplierName(mDeptEntity.getG7SupplierName());
                if (mLineVoTable != null) {
                    request.setLineCode(mLineVoTable.getLineCode());
                }
                request.setLoaderNames(sharedPreferUtil.getEmpName());
                request.setPasscode(mDeptEntity.getPasscode());
                request.setPhone(mDeptEntity.getPhone());
                request.setPlanArriveTime(mDeptEntity.getPlanArriveTime());
                request.setPlanStartTime(mDeptEntity.getPlanStartTime());
                request.setScheduleNo(tvDate.getText().toString() + tvShift.getText().toString());
                request.setShift(tvShift.getText().toString());
                request.setStartcode(mDeptEntity.getStartcode());
                request.setStowageSource(1);
                request.setDestOmgType(mergeDeptType);
                LoaderEntity loaderEntity = new LoaderEntity();
                loaderEntity.setEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
                loaderEntity.setEmpName(sharedPreferUtil.getEmpName());
                loaderEntity.setIsLeader(1);
                List<LoaderEntity> addLoaders = new ArrayList<>();
                addLoaders.add(loaderEntity);
                request.setAddLoaders(addLoaders);
                showPgDlg("创建中...");
                new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                        .setResponsClazz(NoDataResponse.class)
                        .setUrl(Constants.URL_CREATE_STOWAGE)
                        .setRequestObject(request)
                        .execute(new UICallBack() {
                            @Override
                            public void onError(String msg) {
                                dismissPgDlg();
                                if (msg.contains("该配载单已创建")) {
                                    String[] msgSplit = msg.split(":");
                                    if (msgSplit.length > 1) {
                                        String stowageNo = msgSplit[1];
                                        //查询装车任务列表中是否存在此配载单，存在则直接提示跳转装车
                                        queryLoadTask(stowageNo);
                                    }
                                } else {
                                    MyDialog.showAlertDialog(CreateLoadTaskActivity.this, msg);
                                }
                            }

                            @Override
                            public void onSuccess(Object obj) {
                                dismissPgDlg();
                                NoDataResponse response = (NoDataResponse) obj;
                                if (response.getData() != null) {
                                    showToast("创建成功");
                                    toActivity(LoadTaskActivity.class);
                                    finish();
                                }
                            }
                        });
            }

            @Override
            public void onError(Throwable throwable) {
                dismissPgDlg();
                MyDialog.showAlertDialog(CreateLoadTaskActivity.this, "线路查询失败:" + throwable.getMessage());
                SoundVibratorManager.playSound(2);
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 查询装车任务
     *
     * @param stowageNo 配载单
     */
    private void queryLoadTask(final String stowageNo) {
        showPgDlg("查询装车任务中...");
        QueryLoadTaskByStowageRequest request = new QueryLoadTaskByStowageRequest();
        request.setStowageNo(stowageNo);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryLoadTaskByStowageResponse.class)
                .setUrl(Constants.URL_QUERY_LOAD_TASK_BY_STOWAGE)
                .setRequestObject(request)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        etCarNo.setText("");
                        tvNextDeptName.setText("");
                        tvDate.setText("");
                        tvShift.setText("");
                        tvTaskNo.setText("");
                        tvPlanStartTime.setText("");

                        QueryLoadTaskByStowageResponse response = (QueryLoadTaskByStowageResponse) obj;
                        if (response.getData() != null) {
                            QueryLoadTask loadTask = response.getData();
                            if (loadTask.getStowageNo().equals(stowageNo)) {
                                //配载单任务已存在，则提示直接跳转
                                existTaskRemindDialog(loadTask);
                                return;
                            }
                        }
                        showToast("创建成功");
                        toActivity(LoadTaskActivity.class);
                        finish();
                    }
                });
    }

    /**
     * 已存在任务提示框
     */
    private void existTaskRemindDialog(final QueryLoadTask loadTask) {
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("提示");
        dialog.setMessage("该任务已创建，是否前往该任务继续进行装车？");
        dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                UnloadScanTableDao mUnloadScanTableDao = new UnloadScanTableDao();
                List<UnloadScanTable> list = mUnloadScanTableDao.getStowageNoData(loadTask.getStowageNo());
                String task = Constants.getUUID();
                if (list != null && list.size() > 0) {
                    for (UnloadScanTable temp : list) {
                        if (temp.getTask() != null) {
                            task = temp.getTask();
                        }
                    }
                }
                List<LoadTaskEntity> loadTasks = new ArrayList<>();
                loadTasks.add(new LoadTaskEntity(task, loadTask.getStowageNo(), loadTask.getCarMark(), loadTask.getSrcDeptCode(), loadTask.getSrcDeptName(),
                        loadTask.getDestDeptName(), loadTask.getDestDeptCode(), loadTask.getCarNo(), loadTask.getPriceNum() + "",
                        loadTask.getBizTypeCode(), false, loadTask.getPreStartDate(), loadTask.getLoadingLimit(),
                        loadTask.getLoadingProduct(), loadTask.getCarModel(), 0));
                toLoadUnloadGroupActivity(CreateLoadTaskActivity.this, loadTasks);
            }
        });
        dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 请求查询下一部门
     *
     * @param carNo 车牌号
     */
    private void requestQueryNextDept(final String carNo) {
        showPgDlg("查询中...");
        QueryNextDeptRequest request = new QueryNextDeptRequest();
        request.setCarNo(carNo);
        request.setSrcDeptCode(sharedPreferUtil.getDeptCode());
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryNextDeptResponse.class)
                .setUrl(Constants.URL_QUERY_NEXT_DEPT)
                .setRequestObject(request)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                        tvNextDeptName.setText("");
                        tvTaskNo.setText("");
                        tvPlanStartTime.setText("");
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryNextDeptResponse response = (QueryNextDeptResponse) obj;
                        mTaskEntityList = response.getData();
                        if (mTaskEntityList != null && !mTaskEntityList.isEmpty()) {
                            //有任务设置班次为不可选状态
                            tvDate.setEnabled(false);
                            tvShift.setEnabled(false);
                            //有任务显示任务号和预计发车时间，并设置状态
                            llTaskNo.setVisibility(View.VISIBLE);
                            llPlaneStartTime.setVisibility(View.VISIBLE);
                            tvTaskNo.setEnabled(false);
                            tvPlanStartTime.setEnabled(false);
                            //获取优速网点数据
//                            queryUCDeptData(carNo);
                            showMoreNextDeptDialog(mTaskEntityList);
                        } else {
                            //无任务清空数据
                            tvNextDeptName.setText("");
                            tvTaskNo.setText("");
                            tvPlanStartTime.setText("");
                            //无任务设置班次为可选状态
                            tvDate.setEnabled(true);
                            tvShift.setEnabled(true);
                            //无任务隐藏任务号和预计发车时间，并设置状态
                            llTaskNo.setVisibility(View.GONE);
                            llPlaneStartTime.setVisibility(View.GONE);
                            tvTaskNo.setEnabled(true);
                            tvPlanStartTime.setEnabled(true);
                            //查询当前部门是否有该车牌号
                            checkCarNoRequest(carNo);
                        }
                    }
                });
    }

    private void queryUCDeptData(final String carNo) {
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                //查询优速网点
                List<UCDeptTable> ucDeptTableList = new UCDeptTableDao().findAll();
                NextDeptTaskEntity taskEntity = new NextDeptTaskEntity();
                HashMap maps = new HashMap<>();
                for (UCDeptTable item : ucDeptTableList) {
                    maps.put(item.getBaseOrgCode(), item.getOrgName());
                }
                taskEntity.setDeptMaps(maps);
                //设置优速快递部门类型
                taskEntity.setUcDeptType(1);
                taskEntity.setCarNo(carNo);
                mTaskEntityList.add(taskEntity);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                dismissPgDlg();
                showMoreNextDeptDialog(mTaskEntityList);
                SoundVibratorManager.playSound(1);
            }

            @Override
            public void onError(Throwable throwable) {
                dismissPgDlg();
                showToast("本地查询快递网点失败！");
                SoundVibratorManager.playSound(2);
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 无任务的车牌号，请求查询当前部门是否有该车牌号，然后再本地查询下一站
     */
    private void checkCarNoRequest(final String carNo) {
        showPgDlg("校验车牌号中...");
        Map<String, String> params = new HashMap<>(4);
        params.put("vehNo", carNo);
        params.put("currentPage", "1");
        params.put("deptCode", sharedPreferUtil.getDeptCode());
        params.put("compCode", sharedPreferUtil.getCompanyCode());
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_DEPT_CHECK_CAR_NO)
                .setParams(params)
                .setResponsClazz(QueryCarNoResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryCarNoResponse response = (QueryCarNoResponse) obj;
                        if (response.getData() != null) {
                            List<CarNoEntity> carNoEntityList = response.getData().getRecords();
                            if (carNoEntityList != null && !carNoEntityList.isEmpty()) {
                                if (carNoEntityList.get(0).getVehNo().equals(carNo)) {
                                    //支线查询为自有车辆，则不允许创建
                                    mCarNoEntity = carNoEntityList.get(0);
                                    queryCarAttribute(carNo);
                                    return;
                                }
                            }
                        }
                        dismissPgDlg();
                        MyDialog.showAlertDialog(CreateLoadTaskActivity.this, "当前部门无该车牌号！");
                        SoundVibratorManager.playSound(2);
                    }
                });
    }

    /**
     * 查询车辆属性，为自有车辆不允许创建配载单
     */
    private void queryCarAttribute(final String carNo) {
        showPgDlg("查询车辆信息中...");
        Map<String, String> params = new HashMap<>(1);
        params.put("vehNo", carNo);
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_CAR_ATTRIBUTE)
                .setParams(params)
                .setResponsClazz(QueryVehicleAttributeResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryVehicleAttributeResponse response = (QueryVehicleAttributeResponse) obj;
                        if (response.getData() != null) {
                            VehicleEntity entity = response.getData();
                            if (entity != null && entity.getUseType() == 7) {
                                //自有运力不允许创建配载单
                                MyDialog.showAlertDialog(CreateLoadTaskActivity.this, "自有车辆无任务号，不可创建任务！");
                            } else {
                                //非自有运力，本地查询下一站
                                queryLocalNextDept(carNo);
                            }
                        }
                    }
                });
    }

    /**
     * 本地查询下一站
     */
    private void queryLocalNextDept(final String carNo) {
        showPgDlg("查询下一站...");
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                List<String> deptCodes = new ArrayList<>();
                List<LineVoTable> lineList = new LineVoTableDao().findSourceZoneCode(sharedPreferUtil.getDeptCode());
                if (!lineList.isEmpty()) {
                    if (mTaskEntityList == null) {
                        mTaskEntityList = new ArrayList<>();
                    } else {
                        mTaskEntityList.clear();
                    }
                    NextDeptTaskEntity taskEntity = new NextDeptTaskEntity();
                    Map<String, String> maps = new HashMap<>();
                    for (LineVoTable item : lineList) {
                        maps.put(item.getDestZoneCode(), item.getDestZoneName());
                    }
                    taskEntity.setDeptMaps(maps);
                    taskEntity.setCarNo(carNo);
                    mTaskEntityList.add(taskEntity);
                }
                //查询优速网点
                int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
                List<UCDeptTable> ucDeptTableList = new UCDeptTableDao().findAll();
                NextDeptTaskEntity taskEntity = new NextDeptTaskEntity();
                Map<String, String> maps = new HashMap<>();
                for (UCDeptTable item : ucDeptTableList) {
                    if (deptType == 5 || deptType == 6) {
                        //当前登录为分拨，下一站则过滤掉快递分拨
                        if (item.getOrgType() != 21) {
                            maps.put(item.getBaseOrgCode(), item.getOrgName());
                        }
                    } else {
                        maps.put(item.getBaseOrgCode(), item.getOrgName());
                    }
                }
                taskEntity.setDeptMaps(maps);
                //设置优速快递部门类型
                taskEntity.setUcDeptType(1);
                taskEntity.setCarNo(carNo);
                mTaskEntityList.add(taskEntity);

                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                dismissPgDlg();
                showMoreNextDeptDialog(mTaskEntityList);
                SoundVibratorManager.playSound(1);
            }

            @Override
            public void onError(Throwable throwable) {
                dismissPgDlg();
                showToast("本地查询下一站失败！");
                SoundVibratorManager.playSound(2);
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 选择下一站
     */
    private void showMoreNextDeptDialog(final List<NextDeptTaskEntity> dataBeans) {
        if (dataBeans == null || dataBeans.isEmpty()) {
            showToast("未查询到本地下一站！");
            return;
        }
        LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_select_more_task_no, null);
        RecyclerView rvSelectTaskNo = layout.findViewById(R.id.rv_select_task_no);
        EditText etQuerynext = layout.findViewById(R.id.et_query_next);

        final Dialog selectNextDeptDialog = new Dialog(this, R.style.AsyncTaskDialog);
        selectNextDeptDialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        selectNextDeptDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        selectNextDeptDialog.getWindow().getDecorView().setPadding(10, 20, 10, 20);
        selectNextDeptDialog.setCanceledOnTouchOutside(true);

        //当前部门code
        String deptCode = sharedPreferUtil.getDeptCode();
        final List<NextDeptEntity> nextDeptEntityList = new ArrayList<>();
        //获取任务号中的下一站数据
        for (NextDeptTaskEntity item : dataBeans) {
            Map<String, String> maps = item.getDeptMaps();
            if (maps != null) {
                //车线路由
                String[] lineCodes = null;
                if (item.getVehLineCode() != null) {
                    lineCodes = item.getVehLineCode().split(deptCode);
                }
                for (Map.Entry<String, String> entry : maps.entrySet()) {
                    //没有车线路由都展示下一站，否则截取在当前部门之后的车线路由作为下一站展示
                    if (lineCodes == null || (lineCodes.length > 1 && lineCodes[1].contains(entry.getKey()))) {
                        NextDeptEntity nextDeptEntity = new NextDeptEntity();
                        nextDeptEntity.setTaskNo(item.getTaskNo());
                        nextDeptEntity.setCarModel(item.getCarModel());
                        nextDeptEntity.setDriverName(item.getDriverName());
                        nextDeptEntity.setDriverPhone(item.getDriverPhone());
                        nextDeptEntity.setDriverCode(item.getDriverCode());
                        nextDeptEntity.setG7SupplierName(item.getG7SupplierName());
                        nextDeptEntity.setStartcode(item.getStartcode());
                        nextDeptEntity.setPasscode(item.getPasscode());
                        nextDeptEntity.setEndcode(item.getEndcode());
                        nextDeptEntity.setPhone(item.getPhone());
                        nextDeptEntity.setPlanArriveTime(item.getPlanArriveTime());
                        nextDeptEntity.setPlanStartTime(item.getPlanStartTime());
                        nextDeptEntity.setShift(item.getShift());
                        nextDeptEntity.setScheduleNo(item.getScheduleNo());
                        nextDeptEntity.setScheduleNo(item.getScheduleNo());
                        nextDeptEntity.setCarNo(item.getCarNo());
                        nextDeptEntity.setNextDeptCode(entry.getKey());
                        nextDeptEntity.setNextDeptName(entry.getValue());
                        nextDeptEntity.setUseType(item.getUseType());
                        nextDeptEntityList.add(nextDeptEntity);
                    }
                }
            }
        }

        final List<NextDeptEntity> tempList = new ArrayList<>();
        tempList.addAll(nextDeptEntityList);

        //根据时间倒序排序
//        Collections.reverse(nextDeptEntityList);

        final SelectMoreTaskNoAdapter adapter = new SelectMoreTaskNoAdapter(this, nextDeptEntityList, new CommonViewHolder.onItemCommonClickListener() {
            @Override
            public void onItemClickListener(int position) {
                mDeptEntity = nextDeptEntityList.get(position);
                if (mDeptEntity.getNextDeptName() != null) {
                    tvNextDeptName.setText(mDeptEntity.getNextDeptName());
                }
                if (mDeptEntity.getScheduleNo() != null) {
                    tvDate.setText(mDeptEntity.getScheduleNo().substring(0, mDeptEntity.getScheduleNo().length() - 2));
                    tvShift.setText(mDeptEntity.getScheduleNo().substring(mDeptEntity.getScheduleNo().length() - 2, mDeptEntity.getScheduleNo().length()));
                }
                if (mDeptEntity.getPlanStartTime() != null) {
                    tvPlanStartTime.setText(mDeptEntity.getPlanStartTime());
                }
                if (mDeptEntity.getTaskNo() != null) {
                    tvTaskNo.setText(mDeptEntity.getTaskNo());
                }
                if (mDeptEntity.getUcDeptType() == 1) {
                    //优速网点无需填写班次，则隐藏
                    llShift.setVisibility(View.GONE);
                } else {
                    llShift.setVisibility(View.VISIBLE);
                }
                selectNextDeptDialog.dismiss();
            }

            @Override
            public void onItemLongClickListener(int position) {

            }
        });
        rvSelectTaskNo.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rvSelectTaskNo.setAdapter(adapter);
        selectNextDeptDialog.show();

        etQuerynext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    String nextDept = s.toString();
                    List<NextDeptEntity> lists = new ArrayList<>();
                    for (NextDeptEntity item : tempList) {
                        if (item.getNextDeptName() != null) {
                            if (item.getNextDeptName().contains(nextDept)) {
                                lists.add(item);
                            }
                        }
                    }
                    nextDeptEntityList.clear();
                    nextDeptEntityList.addAll(lists);
                    adapter.notifyDataSetChanged();
                } else {
                    nextDeptEntityList.clear();
                    nextDeptEntityList.addAll(tempList);
                    adapter.notifyDataSetChanged();
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }


    private class AddTextChangedListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            //车牌号英文字母转换成大写
            String carNo = etCarNo.getText().toString().toUpperCase();
            if (!carNo.equalsIgnoreCase(mTempCarNo) && !"".equals(carNo)) {
                mTempCarNo = carNo;
                etCarNo.setText(carNo);
                etCarNo.setSelection(carNo.length());
            }
            changeCarNo = true;
        }
    }
}
